﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.客户管理;
using SmartProduction.Domain.客户管理.WorkOrder;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.work_InvoiceCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.work_InvoiceHandler
{
    /// <summary>
    /// 基础信息新建命令处理
    /// </summary>
    public class work_InvoiceCreateCommandHandler : IRequestHandler<work_InvoiceCreateCommand, APIResult<object>>
    {
        /// <summary>
        /// 基础信息仓储
        /// </summary>
        private readonly IBaseRepository<work_Invoice> invoiceRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="invoiceRepository">基础信息仓储</param>
        /// <param name="mapper">映射</param>
        public work_InvoiceCreateCommandHandler(IBaseRepository<work_Invoice> invoiceRepository,IMapper mapper)
        {
            this.invoiceRepository = invoiceRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回</returns>
        public Task<APIResult<object>> Handle(work_InvoiceCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<object> result = new APIResult<object>();

                DateTime date = DateTime.Now;
                string dateString = date.ToString("yyyyMMddHHmmss");
                string bianma = dateString;

                var obj = mapper.Map<work_Invoice>(request);

                obj.InvoiceCode = "KPDH" + bianma;
                
                var r = invoiceRepository.AddAsync(obj).Result;

                if (r > 0)
                {
                    result.Code = APIEnums.添加成功;
                    result.Msg = APIEnums.添加成功.ToString();
                    result.data = r;
                }
                else
                {
                    result.Code = APIEnums.添加失败;
                    result.Msg = APIEnums.添加失败.ToString();
                    result.data = r;
                }

                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
